package com.valuegroup.smarttodo.ui.programme.goals;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.Goals;
import com.valuegroup.smarttodo.data.vo.TagVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.chip.Chip;
import com.valuegroup.smarttodo.plugins.chip.OnCloseClickListener;
import com.valuegroup.smarttodo.plugins.chip.OnSelectClickListener;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoalsTagActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.back_wrapper)
    FrameLayout backWrapper;
    @BindView(R.id.labHeaderTitle)
    TextView labHeaderTitle;
    @BindView(R.id.editTagAdd)
    EditText editTagAdd;
    @BindView(R.id.fbAll)
    FlexboxLayout fbAll;
    @BindView(R.id.fbChose)
    FlexboxLayout fbChose;
    @BindView(R.id.btnDel)
    TextView btnDel;
    private Long DATA_ID;
    private Integer DATA_POSITION;
    private Goals DATA;
    private boolean isDelStatus = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goals_tag);
        ButterKnife.bind(this);


        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getGoalsService().getGoalsDao().load(DATA_ID);


        editTagAdd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus) {
                    // 失去焦点
                    if (!TextUtils.isEmpty(editTagAdd.getText().toString())) {
                        ServiceFactory.getInstance().getTagService().addTagAndSaveGoalRelate(editTagAdd.getText().toString(), DATA_ID);
                        editTagAdd.setText("");
                        inflateTag();
                    }
                }
            }
        });

        editTagAdd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    if (!TextUtils.isEmpty(v.getText())) {
                        ServiceFactory.getInstance().getTagService().addTagAndSaveGoalRelate(editTagAdd.getText().toString(), DATA_ID);

                        // 清空数据
                        v.setText(null);
                        inflateTag();
                    }
                }
                return true;
            }
        });


        inflateTag();
    }

    private void inflateTag() {
        // 已选标签
        inflateLayoutWithTags(fbChose, false);
        // 全部标签
        if (isDelStatus) {
            inflateLayoutWithTagsForDelStatus(fbAll);
        } else {
            inflateLayoutWithTags(fbAll, true);
        }
    }

    private void inflateLayoutWithTags(FlexboxLayout fb, boolean all) {
        fb.removeAllViews();
        List<TagVo> tags = ServiceFactory.getInstance().getTagService().findTagForGoal(DATA.getId(), all);
        for (TagVo vo : tags) {
            View tagView = getLayoutInflater().inflate(R.layout.single_tag, null);
            Chip tag = tagView.findViewById(R.id.tag);
            tag.setChipText(vo.getTitle());
            tag.setTagId(vo.getId());
            if (all) {
                if (vo.isChose()) {
                    tag.setSelected(true);
                }
                tag.setOnSelectClickListener(new OnSelectClickListener() {
                    @Override
                    public void onSelectClick(View v, Long tagId, boolean selected) {
                        if (selected) {
                            ServiceFactory.getInstance().getTagService().addTagForGoal(DATA.getId(), tagId);
                        } else {
                            ServiceFactory.getInstance().getTagService().delTagForGoal(DATA.getId(), tagId);
                        }
                        inflateTag();
                    }
                });
            } else {
                tag.setClosable(true);
                tag.setOnCloseClickListener(new OnCloseClickListener() {
                    @Override
                    public void onCloseClick(View v, Long tagId) {
                        ServiceFactory.getInstance().getTagService().delTagForGoal(DATA.getId(), tagId);
                        inflateTag();
                    }
                });
            }

            fb.addView(tagView);
        }
    }

    private void inflateLayoutWithTagsForDelStatus(FlexboxLayout fb) {
        fb.removeAllViews();
        List<TagVo> tags = ServiceFactory.getInstance().getTagService().findAllTag();
        for (TagVo vo : tags) {
            View tagView = getLayoutInflater().inflate(R.layout.single_tag, null);
            Chip tag = tagView.findViewById(R.id.tag);
            tag.setChipText(vo.getTitle());
            tag.setTagId(vo.getId());
            tag.setClosable(true);
            tag.setOnCloseClickListener(new OnCloseClickListener() {
                @Override
                public void onCloseClick(View v, Long tagId) {
                    boolean exist = ServiceFactory.getInstance().getTagService().existRelate(tagId);
                    if (exist) {
                        AlertUtils.delOrderDialog(GoalsTagActivity.this,
                                String.format(getResources().getString(R.string.alt_del_tag), vo.getTitle()),
                                (dialog, which) -> {
                                    ServiceFactory.getInstance().getTagService().delTag(tagId);
                                    inflateTag();
                                });
                    } else {
                        ServiceFactory.getInstance().getTagService().delTag(tagId);
                        inflateTag();
                    }

                }
            });
            fb.addView(tagView);
        }
    }

    @OnClick({R.id.btnBack, R.id.btnDel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnDel:
                isDelStatus = !isDelStatus;
                inflateTag();
                btnDel.setText(getResources().getText(isDelStatus ? R.string.op_cancel : R.string.op_delete));
                break;
            case R.id.btnBack:
                finishAfterTransition();
                break;
        }
    }
}
